#!/bin/sh

MOKOTOUCH_DISTDIR="MOKOTOUCH-DIST"
MOKOTOUCH_APPS_DIR="$MOKOTOUCH_DISTDIR/Apps"
MOKOTOUCH_CORESERVICES_DISTDIR="$MOKOTOUCH_DISTDIR/CoreServices"
MOKOTOUCH_FRAMEWORKS_DIR="$MOKOTOUCH_DISTDIR/Frameworks"
BUILD_SIMULATOR="0"
BUILDARGS=""

CORESERVICES_SRC="./MokoTouch/CoreServices"
FRAMEWORKS_SRC="./MokoTouch/Frameworks"
APPS_SRC="./MokoTouch/Apps"

UIKIT_LINK="../../Frameworks/UIKit/UIKit.framework/"

CORESERVICE_LIST="MokoTouch"
FRAMEWORK_LIST="UIKit"
APP_LIST="Homescreen CustomTableView HelloWorld TestKeyboard TestTableView"

SILENT_CDBACK="cd ../../../ &> /dev/null"

for arg; do
    if [ "$arg" = "--simulator" ]; then
        BUILD_SIMULATOR="1"
        BUILDARGS="$BUILDARGS --simulator"
    elif [ "$arg" = "--help" ]; then
        exit 1
    fi
done

if [ "$BUILD_SIMULATOR" = "1" ]; then
    echo "Build Moko Touch (Simulator)"
else
    echo "Build Moko Touch"
fi

# Build Frameworks
for framework in $FRAMEWORK_LIST; do
    cd $FRAMEWORKS_SRC/$framework/ && sh build-framework.sh $BUILDARGS && $SILENT_CDBACK
    if [ $? -ne 0 ]; then
        echo " - Moko Touch Build Failed at Framework '$framework' [ !! ]"
        exit 1
    fi
done

# Build Core Services
for coreService in $CORESERVICE_LIST; do
    rm -f $CORESERVICES_SRC/$coreService/UIKit.framework
    cd $CORESERVICES_SRC/$coreService/ &&  ln -s $UIKIT_LINK . && sh build-service.sh $BUILDARGS && $SILENT_CDBACK
    if [ $? -ne 0 ]; then
        echo " - Moko Touch Build Failed at Core Service '$coreService' [ !! ]"
        exit 1
    fi
done

# Build Apps
for app in $APP_LIST; do
    rm -f $APPS_SRC/$app/UIKit.framework    
    echo `pwd`
    cd $APPS_SRC/$app/ && ln -s $UIKIT_LINK . && sh build-app.sh $BUILDARGS && $SILENT_CDBACK
    if [ $? -ne 0 ]; then
        echo " - Moko Touch Build Failed at App '$app' [ !! ]"
        exit 1
    fi
done    

echo "Paking Moko Touch"
rm -rf $MOKOTOUCH_DISTDIR
mkdir -p $MOKOTOUCH_APPS_DIR
mkdir -p $MOKOTOUCH_APPS_DIR/Dock
mkdir -p $MOKOTOUCH_FRAMEWORKS_DIR
mkdir -p $MOKOTOUCH_CORESERVICES_DISTDIR

# Pack Frameworks
for framework in $FRAMEWORK_LIST; do
    cp -R $FRAMEWORKS_SRC/$framework/$framework.framework/ $MOKOTOUCH_FRAMEWORKS_DIR
done

# Pack Core Services
for coreService in $CORESERVICE_LIST; do
    cp $CORESERVICES_SRC/$coreService/BUILD/Service/$coreService $MOKOTOUCH_CORESERVICES_DISTDIR
done

# Build Apps
for app in $APP_LIST; do
    cp -R $APPS_SRC/$app/$app.app/ $MOKOTOUCH_APPS_DIR
done

